<?php

namespace app\api\controller;

use app\api\extend\Common;
use think\facade\Db;

class HomeRequirement extends Common
{
    public function add() {
        // $res = $this->check_params();
        // if (!empty($res)) return $res;
        $data = array_merge($this->params,['muser_id'=>$this->request->auth['userId']]);
        $res = $this->model->add($data);
        if (!$res){
            return $this->return_msg(400,'添加需求失败');
        }
        $user = Db::name('home_muser')->where('id',$this->request->auth['userId'])->find();
        $result = Db::name('home_muser')
        ->where('id',$this->request->auth['userId'])
        ->update([
            'release_req' => $user['release_req'] += 1
        ]);
        if (!$result){
            return $this->return_msg(400,'添加需求失败');
        }
        return $this->return_msg(200,'添加需求成功',['id'=>$res]);
    }

    public function list() {
        $word = $this->params['word']??'';
        $sortType = $this->params['sortType']??0;//排序类型 0时间 1兑换币
        $order=[
            "name"=>"a.id",
            "sort"=>"desc",
        ];
        if ($sortType==1) {
           $order['name']="a.price";       
           $order['sort']="desc";       
        }    
        $where = [
            // ['a.muser_id','<>',$this->request->auth['userId']],
            ['a.status','=',0],
        ];

        $res = Db::name('home_requirement')
        ->alias('a')
        ->join('home_muser b','a.muser_id = b.id')
        ->where($where)
        ->where('a.name','like',"%{$word}%")
        ->field('a.id,a.name as title,a.content,a.pic_image,a.price,a.service_time,a.service_duration,a.serve_com,a.status,b.id as user_id,b.name,b.age,b.avatar_image,b.habitability,b.release_req,b.good_reput,b.user_type,b.exchan_coin,b.mark,a.create_time')
        ->order($order["name"],$order["sort"])
        ->select();
        if (empty($res)) {
             return $this->return_msg(400,'获取失败');
        }
        
        return $this->return_msg(200,'获取成功',$res->toArray());
    }

        public function detail() {
        $id = $this->params['id']??'';

        $where = [
            // ['a.status','=',0],
        ];
        if (!empty($id)) {
            $where[] = ['a.id','=',$id];
        }

        $res = Db::name('home_requirement')
        ->alias('a')
        ->join('home_muser b','a.muser_id = b.id')
        ->where($where)
        ->field('a.id,a.name as title,a.content,a.pic_image,a.price,a.service_time,a.service_duration,a.serve_com,a.status,b.id as user_id,b.name,b.age,b.avatar_image,b.habitability,b.release_req,b.good_reput,b.user_type,b.exchan_coin,b.mark,a.create_time')
        ->select();
        if (empty($res)) {
             return $this->return_msg(400,'获取失败');
        }
        
        return $this->return_msg(200,'获取成功',$res->toArray());
    }

    public function serverNoList() {
        $where = [
            ['a.status','>',0],
            ['a.status','<',3],
        ];
        if ($this->request->auth['user_type']==0) {
             $where[] = ['a.muser_id','=',$this->request->auth['userId']];
        }else{
             $where[] = ['a.accpet_muser_id','=',$this->request->auth['userId']];
        }
        $res = Db::name('home_requirement')
        ->alias('a')
        ->join('home_muser b','b.id = a.muser_id')
        ->where($where)
        ->field('a.id,a.name as title,a.content,a.pic_image,a.price,a.service_time,a.service_duration,a.serve_com,a.status,b.id as user_id,b.name,b.age,b.avatar_image,b.habitability,b.release_req,b.good_reput,b.user_type,b.exchan_coin,b.mark,a.create_time')
        ->select();
        if (empty($res)) {
             return $this->return_msg(400,'获取失败');
        }
        
        return $this->return_msg(200,'获取成功',$res->toArray());
    }

     public function serverOkList() {
        $where = [
            ['a.status','=',3],
        ];
        if ($this->request->auth['user_type']==0) {
             $where[] = ['a.muser_id','=',$this->request->auth['userId']];
        }else{
             $where[] = ['a.accpet_muser_id','=',$this->request->auth['userId']];
        }
        $res = Db::name('home_requirement')
        ->alias('a')
        ->join('home_muser b','b.id = a.muser_id')
        ->where($where)
        ->field('a.id,a.name as title,a.content,a.pic_image,a.price,a.service_time,a.service_duration,a.serve_com,a.status,b.id as user_id,b.name,b.age,b.avatar_image,b.habitability,b.release_req,b.good_reput,b.user_type,b.exchan_coin,b.mark,a.create_time')
        ->select();
        if (empty($res)) {
             return $this->return_msg(400,'获取失败');
        }
        
        return $this->return_msg(200,'获取成功',$res->toArray());
    }

    public function del()
    {
         $res = $this->check_params();
        if (!empty($res)) return $res;
        
        $res = $this->model->del($this->params['id']);
        if (!$res){
            return $this->return_msg(400,'删除失败');
        }
        return $this->return_msg(200,'删除成功',['count'=>$res],false);
    }

    public function update()
    {
        $res = $this->check_params();
        if (!empty($res)) return $res;

        $newData = [
            'id'=>$this->params['id'],
        ];
        $newData['data'] = array_diff_key($this->params,array_keys($newData));
        $res = $this->model->upd($newData);
        if (!$res){
            return $this->return_msg(400,'修改失败');
        }
        return $this->return_msg(200,'修改成功',['count'=>$res],false);
    }

    public function history()
    {
        $where = [
            ['a.muser_id','=',$this->request->auth['userId']],
        ];
        $res = Db::name('home_requirement')
        ->alias('a')
        ->join('home_muser b','b.id = a.accpet_muser_id')
        ->where($where)
        ->select();

        if (empty($res)) {
             return $this->return_msg(400,'获取失败');
        }
        
        return $this->return_msg(200,'获取成功',$res->toArray());
    }

    public function status()
    {
        $where = [
            ['id','=',$this->params['id']],
        ];
        $res = Db::name('home_requirement')
        ->where($where)
        ->update([
            'status'=>$this->params['status']
        ]);

        if (!$res) {
            return $this->return_msg(400,'修改状态失败');
        }

         return $this->return_msg(200,'修改状态成功');
    }

    public function accept()
    {
        $where = [
            ['id','=',$this->params['id']],
        ];
        $res = Db::name('home_requirement')
        ->where($where)
        ->update([
            'accpet_muser_id'=>$this->request->auth['userId']
        ]);

        if (!$res) {
            return $this->return_msg(400,'接受需求用户失败');
        }
        $res = Db::name('home_requirement')
            ->where($where)
            ->update([
                'status'=>1
            ]);
        if (!$res) {
           return $this->return_msg(400,'接受需求用户失败');
        }
         return $this->return_msg(200,'接受需求用户成功');
    }

    public function completion()
    {
        // $price = $this->params['price'];
        $req_id = $this->params['req_id'];
        $help_minues = $this->params['help_minues'];

        $req = Db::name('home_requirement')->where('id' , $this->params['req_id'])->find();
        if (empty($req)){
            return $this->return_msg(400,'未查找到需求');
        }
        $price = $req['price'];
        $user = Db::name('home_muser')->where('id' , $this->request->auth['userId'])->find();
        if (empty($user)) {
                   return $this->return_msg(500,'未查找到用户信息');
        }
        $res = Db::name('home_muser')->where('id' , $this->request->auth['userId'])
        ->update([
            'exchan_coin' => $user['exchan_coin'] +=  $price,
            'help_count' => $user['help_count'] += 1,
            'help_minues' => $user['help_minues'] += $help_minues,
        ]);
        if (!$res) {
           return $this->return_msg(500,'更新余额失败');
        }

         // 保存订单信息
        $res = Db::name('home_reqorder')->save([
            'muser_id' => $this->request->auth['userId'],
            'amount' => $price,
            'req_id' => $this->params['req_id'],
            'status' => 1, // 假设订单状态为已支付
        ]);
        
        // 其他订单信息...
 
        if (empty($res)) {
            // 如果订单保存失败，回滚余额操作
            $user['exchan_coin'] -=  $price;
            Db::name('home_muser')->where('id' , $this->request->auth['userId'])
            ->update([
                'exchan_coin' => $user['exchan_coin'] -=  $price
            ]);
            return $this->return_msg(500,'保存订单失败');
        }

         return $this->return_msg(200,'保存订单成功');
    }
}